//
//  LevelChoosingScene.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 9/7/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "LevelChoosingScene.h"
#import "LevelManager.h"
#import "MenuScene.h"
#import "MainGameScene.h"
#import "CCMenuItemSpriteBatch.h"
#import "CCLabelBMFontBatch.h"
#import "ShopScene.h"
#import "Utility.h"

@implementation LevelChoosingScene

+(CCScene *) scene
{
    CCScene *scene = [CCScene node];
    LevelChoosingScene *layer = [LevelChoosingScene node];
    [scene addChild:layer];
    return scene;
}

+(CCScene *) sceneEx
{
    CCScene *scene = [CCScene node];
    LevelChoosingScene *layer = [LevelChoosingScene node];
    [layer jumpToPageEnd];
    [scene addChild:layer];
    return scene;
}

-(id) init
{
    if (self = [super init])
    {
        [self create];
    }
    
    return self;
}


-(void) create
{
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CCMenu *mainmenu = [[CCMenu alloc] init];
    [mainmenu setPosition:CGPointZero];
    
    CCMenuItem *mMIBack = [CCMenuItemSprite itemWithNormalSprite:[CCSprite spriteWithSpriteFrameName:SFN_BACK]
                                                 selectedSprite:nil
                                                         target:self
                                                       selector:@selector(onBack)];
    [mMIBack setPosition:uniPos(ccp(winSize.width - 20, winSize.height - 20), ccp(winSize.width - 40, winSize.height - 40))];
    mMIBack.activeArea = CGRectMake(-20, -20, mMIBack.contentSize.width + 40, mMIBack.contentSize.height + 40);
    [mainmenu addChild:mMIBack];
    [self addChild:mainmenu];
    
    
    CCSprite *circle = [CCSprite spriteWithSpriteFrameName:SFN_CIRCLE_80];
    CCSprite *shop = [CCSprite spriteWithSpriteFrameName:SFN_ICON_SHOP];
    [shop setPosition:ccp(circle.contentSize.width / 2, circle.contentSize.width / 2)];
    [circle addChild:shop];
    
    CCSprite *circleHover = [CCSprite spriteWithSpriteFrameName:SFN_CIRCLE_80];
    CCSprite *shopHover = [CCSprite spriteWithSpriteFrameName:SFN_ICON_SHOP];
    
    [shopHover setPosition:ccp(circle.contentSize.width / 2, circle.contentSize.width / 2)];
    [circleHover addChild:shopHover];
    
    [circleHover setColor:CL_PANEL_BTN];
    [shopHover setColor:CL_PANEL_BTN];
    CCMenuItem *miShop = [CCMenuItemSprite itemWithNormalSprite:circle selectedSprite:circleHover block:^(id sender) {
        CCLOG(@"open shop");
        [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
        [[CCDirector sharedDirector] pushScene:[CCTransitionFade transitionWithDuration:0.5 scene:[ShopScene scene]]];
    }];
    [miShop setPosition:uniPos(ccp(winSize.width - 30, 40), ccp(winSize.width - 60, 80))];
    [mainmenu addChild:miShop];
    
    // info
    int numStar = [[LevelManager getInstance] getNumStar];
    int maxStar = [[LevelManager getInstance] getNumMaxStar];
    CCLabelBMFont *lbStar = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"Total: %d/%d", numStar, maxStar]
                                                   fntFile:FONT_DEFAULT];
    [lbStar setAnchorPoint:ccp(0, 0.5)];
    [lbStar setPosition:uniPos(ccp(20, winSize.height - 20), ccp(40, winSize.height - 40))];
    [lbStar setAlignment:kCCTextAlignmentCenter];
    [self addChild:lbStar];
    
    CCSprite *starIcon = [CCSprite spriteWithSpriteFrameName:SFN_ICON_STAR_SMALL];
    [starIcon setPosition:ccp(lbStar.position.x + lbStar.contentSize.width + uniPos(15, 30), lbStar.position.y)];
    [self addChild:starIcon];
    
    // create menu
    
    NSMutableArray *arrayPages = [NSMutableArray array];
    int numLevel = [[LevelManager getInstance] getNumLevel];
    int numLevelPerPage = 20;
    float startX = uniPos(50, 150);
    float paddleX = (winSize.width - 2 * startX) / 3;
    float startY = winSize.height / 2 + uniPos(170, 340);
    float x = startX;
    float y;
    CCMenu *page;
    CCSpriteBatchNode *sprBatch;
    CCSpriteBatchNode *fntBatch;
    
    for (int i = 0; i < numLevel; i++)
    {
        // create new page if needed
        if (i % numLevelPerPage == 0) // first item of page
        {
            
            CCLayer *layerPage = [CCLayer node];
            page = [CCMenu menuWithArray:nil];
            [page setPosition:CGPointZero];
            [layerPage addChild:page];
            [arrayPages addObject:layerPage];
            
            sprBatch = [CCSpriteBatchNode batchNodeWithFile:IMAGE_UI];
            [layerPage addChild:sprBatch];
            
            fntBatch = [CCSpriteBatchNode batchNodeWithFile:IMAGE_FONT_DEFAULT];
            [layerPage addChild:fntBatch];
            
            y = startY;
        }
        
        x = startX + ((i - 0) % 4) * paddleX;
        
        
        // Get properties
        BOOL isLevelAvailabel = i <= [LevelManager getInstance]._maxReachLevel;
        int numStar = [[LevelManager getInstance] getLevelDetail:i]._star;
        
        
        // create item
        CCSprite *spr = [CCSprite spriteWithSpriteFrameName:SFN_CIRCLE_80];
        CCSprite *sprHover = [CCSprite spriteWithSpriteFrameName:SFN_CIRCLE_80];
        CCSprite *sprDisable = [CCSprite spriteWithSpriteFrameName:SFN_CIRCLE_80];
        
        [sprHover setColor:CL_PANEL_BTN];
        [sprDisable setColor:CL_HAFT_WHITE];
        
        [sprBatch addChild:spr];
        [sprBatch addChild:sprHover];
        [sprBatch addChild:sprDisable];
        
        // create menu item
        CCMenuItem *mi = [CCMenuItemSpriteBatch itemWithNormalSprite:spr
                                                      selectedSprite:sprHover
                                                      disabledSprite:sprDisable
                                                              target:self
                                                            selector:@selector(onItemClick:)];
        mi.activeArea = CGRectMake(-20, -20, mi.contentSize.width + 40, mi.contentSize.height + 40);
        [mi setTag:i];
        [mi setPosition:ccp(x, y)];
        [page addChild:mi];
        
        // create label
        CCLabelBMFontBatch *lb = [CCLabelBMFontBatch labelWithString:[NSString stringWithFormat:@"%d", i + 1] fntFile:FONT_DEFAULT];
        [lb setAnchorPoint:ccp(0.5, 0.5)];
        [lb setPosition:ccp(mi.position.x, mi.position.y)];
        
        // check if level available
        if (!isLevelAvailabel)
        {
#warning turn off is enable for level testing
//            mi.isEnabled = NO; // for test
            [lb setColor:CL_HAFT_WHITE];
        }
        [lb addToBatch:fntBatch];
        
        [self createStar:numStar batch:sprBatch position:mi.position];
        // adjust position
        if (i % 4 == 3)
        {
            y -= uniPos(75, 150);
        }
    }
    
    CCLayer *layerComingSoon = [CCLayer node];
    CCLabelBMFontBatch *lbcms = [CCLabelBMFontBatch labelWithString:@"More level comming soon!" fntFile:FONT_DEFAULT];
    [lbcms setAnchorPoint:ccp(0.5, 0.5)];
    [lbcms setPosition:ccp(winSize.width / 2, winSize.height / 2)];
    [layerComingSoon addChild:lbcms];
    [arrayPages addObject:layerComingSoon];
    
    mScrollLayer = [CCScrollLayer nodeWithLayers:arrayPages widthOffset:0];
    mScrollLayer.minimumTouchLengthToChangePage = 40;
    mScrollLayer.minimumTouchLengthToSlide = 10;
    mScrollLayer.marginOffset = [CCDirector sharedDirector].winSize.width / 2;
    mScrollLayer.showPagesIndicator = YES;
    mScrollLayer.pagesIndicatorPosition = ccp(winSize.width / 2, startY - uniPos(375, 750));
    
    [self addChild:mScrollLayer];
    
    if ([LevelManager getInstance]._currentLevel == -1)
    {
        int currentPage = [LevelManager getInstance]._maxReachLevel / numLevelPerPage;
        [mScrollLayer selectPage:currentPage];
//        CCLOG(@"level = %d", [LevelManager getInstance]._maxReachLevel);
//        CCLOG(@"page = %d", currentPage);
    }
    else
    {
        int currentPage = [LevelManager getInstance]._currentLevel / numLevelPerPage;
        [mScrollLayer selectPage:currentPage];
    }
}

-(void) createStar:(int)star batch:(CCSpriteBatchNode *)batch position:(CGPoint)position
{
    for (int i = 0; i < star; i++)
    {
        CCSprite *spr = [CCSprite spriteWithSpriteFrameName:SFN_ICON_STAR_SMALL];
        [batch addChild:spr];
        
        if (i == 0) [spr setPosition:ccpAdd(position, uniPos(ccp(-17, -28), ccp(-34, -56)))];
        else if (i == 1) [spr setPosition:ccpAdd(position, uniPos(ccp(0, -33), ccp(0, -66)))];
        else if (i == 2) [spr setPosition:ccpAdd(position, uniPos(ccp(17, -28), ccp(34, -56)))];
    }
}

-(void) onItemClick:(NSObject *)sender
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
//    CCLOG(@"onItemClick");
    CCMenuItem *mi = (CCMenuItem *)sender;
//    CCLOG(@"tag = %d", mi.tag);
    
    [LevelManager getInstance]._currentLevel = mi.tag;
    [LevelManager getInstance]._isNewLevel = YES;
    [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[MainGameScene scene]]];
    
}

-(void) onBack
{
    [[Utility getInstance] playEffect:SOUND_MENU_BUTTON];
    [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:0.5 scene:[MenuScene scene]]];
}

-(void) jumpToPageEnd
{
    [mScrollLayer selectPage:mScrollLayer.pages.count - 1];
}

@end
